package com.nl.mobile.commuteaid.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.nl.mobile.commuteaid.data.TFLStationStatus;

import android.util.Xml;

public class TFLFeedParser {
	// Indicate that we don't user namespaces in XML parser
	private static final String ns = null;
	private XmlPullParser xmlParser;
	private List<TFLStationStatus> stationStatuses;

	public TFLFeedParser() {
		this.xmlParser = Xml.newPullParser();
        try {
			this.xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
	}
	
	public List<TFLStationStatus> fetchStationStatues(InputStream input) throws XmlPullParserException, IOException {
		if(this.stationStatuses==null) {
			this.stationStatuses = new ArrayList<TFLStationStatus>();
			this.refreshStationStatues(input, this.stationStatuses);
		}
		return this.stationStatuses;
	}

	public void refreshStationStatues(InputStream input, List<TFLStationStatus> stationStatusesParam)
			throws XmlPullParserException, IOException {
		stationStatusesParam.clear();
		this.xmlParser.setInput(input, null);
		this.xmlParser.nextTag();
		this.xmlParser.require(XmlPullParser.START_TAG, ns, "ArrayOfLineStatus");
	    while (this.xmlParser.next() != XmlPullParser.END_TAG) {
	        if (this.xmlParser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        String name = this.xmlParser.getName();
	        // Starts by looking for the 'LineStatus' tag
	        if (name.equals("LineStatus")) {
	            TFLStationStatus stationStatus = new TFLStationStatus();
	            stationStatus.setStatusDetails(this.xmlParser.getAttributeValue(ns, "StatusDetails"));
	            while(this.xmlParser.next()!=XmlPullParser.START_TAG || !"Line".equals(this.xmlParser.getName())) {
	            	continue;
	            }
	            stationStatus.setLineName(this.xmlParser.getAttributeValue(ns,  "Name"));
	            stationStatus.setLineId(this.xmlParser.getAttributeValue(ns, "ID"));
	            while(this.xmlParser.next()!=XmlPullParser.START_TAG || !"Status".equals(this.xmlParser.getName())) {
	            	continue;
	            }
	            stationStatus.setStatus(this.xmlParser.getAttributeValue(ns, "Description"));
	            stationStatusesParam.add(stationStatus);
	            while(this.xmlParser.next()!=XmlPullParser.END_TAG || !"LineStatus".equals(this.xmlParser.getName())) {
	            	continue;
	            }
	        } else {
	            continue;
	        }
	    }  
	}
}
